﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Gem_Tools;
using Gem_Tools_Controller.Gem_Tools;
using Gem_Tools_Entity.Gem_Tools;
using myExcel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using Gem_Tools_Utility;


namespace GE_Management_Tool.Planning
{
    public partial class frmA0013_Asset : frmBase
    {
        string m_strURL = "";
        int m_iGroup_ID;
        int m_iProject_ID;
        IList<CAsset> m_lsAsset;
        IList<CAsset> m_lsAsset_Import;
        CAsset m_objSelected;
        myExcel.ApplicationClass m_app;
        myExcel.Worksheet m_objSheet;

        public frmA0013_Asset()
        {
            InitializeComponent();
        }

        public void Show_To_Display(int piProject_ID, int piGroup_ID, string p_strGroup_Name)
        {
            m_iGroup_ID = piGroup_ID;
            m_iProject_ID = piProject_ID;
            txtGroupName.Text = p_strGroup_Name;
            this.ShowDialog();
        }

        private void Init_Data()
        {
            m_lsAsset = new List<CAsset>();
            CAsset_Controller v_ctrlAsset = new CAsset_Controller();
            m_lsAsset = v_ctrlAsset.A0013_List_Asset_By_Project_ID_By_Group_ID(m_iProject_ID, m_iGroup_ID);
            cAssetBindingSource.DataSource = m_lsAsset;
        }

        private string Check_Data()
        {
            StringBuilder v_Sb = new StringBuilder();
            if (m_objSelected.Name == "")
            {
                v_Sb.AppendLine("-Missing Asset Name.");
            }

            return v_Sb.ToString();
        }

        /// <summary>
        /// Hàm xử lý Import dữ liệu vào Excel
        /// </summary>
        /// <param name="p_strFile_Name"></param>
        private void Import_Data(string p_strFile_Name)
        {

            if (m_strURL == "")
            {
                throw new Exception("Please Input File.");
            }
            myExcel.Range range;
            range = m_objSheet.get_Range("A2", Missing.Value);
            range = range.get_End(myExcel.XlDirection.xlToRight);
            range = range.get_End(myExcel.XlDirection.xlDown);

            string downAddress = range.get_Address(
                false, false, myExcel.XlReferenceStyle.xlA1,
                Type.Missing, Type.Missing);

            // Get the range, then values from a1
            range = m_objSheet.get_Range("A2", downAddress.Replace("C", "D"));
            object[,] values = (object[,])range.Value2;
            m_lsAsset_Import = new List<CAsset>();
            for (int i = 1; i <= values.GetLength(0); i++)
            {
                CAsset v_objAsset = new CAsset();
                v_objAsset.Name = values[i, 2].ToString();
                //v_objAsset.Start_Date = DateTime.Parse(values[i, 3].ToString());
                v_objAsset.Start_Date = DateTime.FromOADate(CUtility.Convert_To_Double(values[i, 3]));
                v_objAsset.Manday = double.Parse(values[i, 4].ToString());
                m_lsAsset_Import.Add(v_objAsset);
            }

            CAsset_Controller v_ctrlGroup = new CAsset_Controller();
            if (XtraMessageBox.Show("Are you sure you want to import this file (" + m_lsAsset_Import.Count.ToString() + " records) ?", "Warning", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
            {
                foreach (CAsset v_obj in m_lsAsset_Import)
                {
                    v_obj.Project_ID = m_iProject_ID;
                    v_obj.Group_ID = m_iGroup_ID;
                    v_obj.Auto_ID = v_ctrlGroup.Insert_Asset(v_obj);
                    m_lsAsset.Add(v_obj);
                    
                }
                grdProjectAsset.RefreshDataSource();
                XtraMessageBox.Show("Insert Success !");
            }
        }

        private void grdProjectBatch_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            try
            {
                if (e.Button.ButtonType == NavigatorButtonType.Remove)
                {
                    if (XtraMessageBox.Show("Are you sure you want to delete this Asset ?", "Warning", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                    {
                        CAsset_Controller v_ctrlAsset = new CAsset_Controller();
                        v_ctrlAsset.Delete_Asset(m_objSelected.Auto_ID, CSession.Active_User_Name);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void grvProjectAsset_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                m_objSelected = (CAsset)grvProjectAsset.GetRow(grvProjectAsset.FocusedRowHandle);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void grvProjectAsset_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            try
            {
                string error = Check_Data();
                if (error != "")
                {
                    throw new Exception(error);
                }
                //lúc này là mới thêm vào cho nên Auto ID  = 0;
                if (m_objSelected.Auto_ID <= 0)
                {
                    m_objSelected.Project_ID = m_iProject_ID;
                    m_objSelected.Group_ID = m_iGroup_ID;
                    CAsset_Controller v_ctrlGroup = new CAsset_Controller();
                    m_objSelected.Auto_ID = v_ctrlGroup.Insert_Asset(m_objSelected);
                    XtraMessageBox.Show("Insert Success !");
                }
                else
                {
                    m_objSelected.Project_ID = m_iProject_ID;
                    m_objSelected.Group_ID = m_iGroup_ID;
                    // ở đây là thêm vào hệ thống tự sinh ra auto_id rồi nên auto_id chắc chắn > 0;
                    CAsset_Controller v_ctrlGroup = new CAsset_Controller();
                    v_ctrlGroup.Update_Asset(m_objSelected);
                    XtraMessageBox.Show("Update Success !");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void frmA0013_Asset_Load(object sender, EventArgs e)
        {
            try
            {
                Init_Data();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    m_strURL = openFileDialog1.FileName;
                    if (m_strURL.Contains(".xls") == true || m_strURL.Contains(".xlsx") == true || m_strURL.Contains(".XLS") == true || m_strURL.Contains(".XLSX") == true)
                    {
                        m_app = new Microsoft.Office.Interop.Excel.ApplicationClass();

                        //Khởi tạo các thông tin cần thiết để mở kết nối đến file excel:
                        myExcel.Workbook v_workBook = m_app.Workbooks.Open(m_strURL, 0, true, 5, "", "", true, myExcel.XlPlatform.xlWindows,
                                                                            "\t", false, false, 0, true, 1, 0);
                        m_objSheet = (myExcel.Worksheet)v_workBook.Sheets[1];
                    }
                }

                Import_Data(m_strURL);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
            finally
            {
                m_app.Workbooks.Close();
                m_app.Quit();
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                if(saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    CCommon_Function.Export_To_Excel(grvProjectAsset, saveFileDialog1.FileName);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK);
            }
        }
    }
}